package com.manage.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.manage.dto.PositionDTO;
import com.manage.dto.add.PositionAddDTO;
import com.manage.dto.update.PositionUpdateDTO;
import com.manage.entity.Position;
import com.manage.result.PageResult;
import com.manage.server.mapper.PositionMapper;
import com.manage.server.service.PositionService;
import com.manage.vo.PositionVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @description 针对表【position(职位表)】的数据库操作Service实现
 */
@Service
public class PositionServiceImpl extends ServiceImpl<PositionMapper, Position> implements PositionService {

    @Override
    public boolean save(PositionAddDTO positionAddDTO) {
        Position position = new Position();
        BeanUtils.copyProperties(positionAddDTO, position);
        return this.save(position);
    }

    @Override
    public boolean updateById(PositionUpdateDTO positionUpdateDTO) {
        Position position = new Position();
        BeanUtils.copyProperties(positionUpdateDTO, position);
        return super.updateById(position);
    }

    @Override
    public PageResult<PositionVO> findPositionByPage(PositionDTO dto) {
        // 1. 处理分页参数（默认第1页，每页10条）
        int pageNum = dto.getPageNum() != null && dto.getPageNum() > 0 ? dto.getPageNum() : 1;
        int pageSize = dto.getPageSize() != null && dto.getPageSize() > 0 ? dto.getPageSize() : 10;

        // 2. 创建分页对象
        Page<Position> page = new Page<>(pageNum, pageSize);

        // 3. 构建动态查询条件
        QueryWrapper<Position> queryWrapper = new QueryWrapper<>();

        // 职位名称模糊查询
        if (StringUtils.hasText(dto.getTitle())) {
            queryWrapper.like("title", dto.getTitle().trim());
        }
        if (dto.getParentPosition() != null) {
            queryWrapper.like("parent_position", dto.getParentPosition());
        }

        // 精确匹配条件
        if (dto.getId() != null) {
            queryWrapper.eq("id", dto.getId());
        }

        // 4. 执行分页查询
        Page<Position> resultPage = this.page(page, queryWrapper);

        // 5. 转换Entity到VO
        Page<PositionVO> voPage = (Page<PositionVO>) resultPage.convert(entity -> {
            PositionVO vo = new PositionVO();
            BeanUtils.copyProperties(entity, vo);
            // 可在此处理字段不一致的情况
            return vo;
        });

        // 6. 返回分页结果
        return PageResult.success(voPage);
    }
}